package com.photologics.logic;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayout;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.photologics.main.R;
import com.photologics.main.SelectLogicActivity;
import com.sromku.simple.fb.Permissions;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnPublishListener;
import com.sromku.simple.fb.SimpleFacebookConfiguration;
import com.sromku.simple.fb.entities.Photo;

public class SelectSectionActivity extends Activity implements OnTouchListener {
	private TextView[][] sectionState;
	private TextView logicNameView, playTimeView;
	private GridLayout sectionTable;
	private int sectionCount;
	private String logicName;
	private int[][] Completenss;
	
	String time;

	private SimpleFacebook mFacebook;
	String TAG = "FACEBOOK";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_select_section);
		
		
		 try {
		        PackageInfo info = getPackageManager().getPackageInfo(
		                "com.photologics.main", 
		                PackageManager.GET_SIGNATURES);
		        for (Signature signature : info.signatures) {
		            MessageDigest md = MessageDigest.getInstance("SHA");
		            md.update(signature.toByteArray());
		            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
		            }
		    } catch (NameNotFoundException e) {

		    } catch (NoSuchAlgorithmException e) {

		    }
		
		

		Intent intent = getIntent();
		logicName = intent.getStringExtra(LogicHelper.LOGIC_NAME_PARAMETER);
		if (logicName == null)
			logicName = LogicHelper.logicInfo.getName();
		LogicInfo logicInfo = new LogicInfo(logicName,
				LogicHelper.db.getValue(logicName),
				LogicHelper.db.getCompleteness(logicName),
				LogicHelper.db.getState(logicName));
		LogicHelper.logicInfo = logicInfo;

		@SuppressWarnings("deprecation")
		int lcdWidth = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getWidth();

		logicNameView = (TextView) findViewById(R.id.logic_name);
		logicNameView.setText(LogicHelper.logicInfo.getName());
		
		long elapsedSecond = LogicHelper.db.getTime(LogicHelper.logicInfo.getName())/1000;
		long hour = elapsedSecond/3600;
		long minute = elapsedSecond%3600/60;
		long second = elapsedSecond%60;
		time = hour+"시간 "+minute+"분 "+second+"초";
		
		playTimeView = (TextView)findViewById(R.id.played_time);
		playTimeView.setText("플레이 시간 : "+time);

		Completenss = LogicHelper.logicInfo.getCompleteness().clone();
		sectionCount = Completenss.length;
		sectionState = new TextView[sectionCount][sectionCount];

		sectionTable = (GridLayout) findViewById(R.id.grid_section);
		sectionTable.setColumnCount(sectionCount);
		sectionTable.setRowCount(sectionCount);
		sectionTable.setOnTouchListener(this);

		@SuppressWarnings("deprecation")
		Drawable logicImage = new BitmapDrawable(
				LogicHelper.db.getBitmap(logicName));
		sectionTable.setBackgroundDrawable(logicImage);

		Bitmap size = BitmapFactory.decodeResource(getResources(),
				R.drawable.question_mark);
		size = Bitmap.createScaledBitmap(size, lcdWidth / (sectionCount + 1),
				lcdWidth / (sectionCount + 1), true);

		for (int i = 0; i < sectionCount; i++) {
			for (int j = 0; j < sectionCount; j++) {
				sectionState[i][j] = new TextView(this);
				sectionState[i][j].setWidth(lcdWidth / (sectionCount + 1));
				sectionState[i][j].setHeight(lcdWidth / (sectionCount + 1));
				sectionState[i][j].setGravity(Gravity.CENTER);

				sectionState[i][j].setTypeface(null, Typeface.BOLD);
				sectionState[i][j].setText(Integer.toString(Completenss[i][j])
						+ "%");
				
				if (Completenss[i][j] == 100) {
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_100);
					sectionState[i][j].setText(" ");
				} else if (Completenss[i][j] >= 80)
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_80);
				else if (Completenss[i][j] >= 60)
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_60);
				else if (Completenss[i][j] >= 40)
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_40);
				else if (Completenss[i][j] >= 20)
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_20);
				else if (Completenss[i][j] >= 0)
					sectionState[i][j]
							.setBackgroundResource(R.drawable.section_background_0);

				sectionTable.addView(sectionState[i][j]);
			}
		}
		
		Permissions[] permissions = new Permissions[]
				{
					Permissions.BASIC_INFO,
					Permissions.EMAIL,
					Permissions.USER_BIRTHDAY,
					Permissions.USER_PHOTOS,
					Permissions.PUBLISH_ACTION,
					Permissions.PUBLISH_STREAM
				};
		
		SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder()
	    .setAppId("428350570598223")
	    .setPermissions(permissions)
	    .build();
		
		SimpleFacebook.setConfiguration(configuration);
		
		
		//final LoginButton authButton = (LoginButton)findViewById(R.id.authButton);
		ImageButton facebookButton = (ImageButton)findViewById(R.id.facebookButton);
		
		if(LogicHelper.db.getSumCompletness(logicName) == 100)
			facebookButton.setVisibility(View.VISIBLE);
		
		
		facebookButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v){

				OnLoginListener onLoginListener = new SimpleFacebook.OnLoginListener()
				{

				    @Override
				    public void onFail(String reason)
				    {
				        Log.w(TAG, reason);
				    }

				    @Override
				    public void onException(Throwable throwable)
				    {
				        Log.e(TAG, "Bad thing happened", throwable);
				    }

				    @Override
				    public void onThinking()
				    {
				        // show progress bar or something to the user while login is happening
				        Log.i(TAG, "In progress");
				    }

				    @Override
				    public void onLogin()
				    {
				        // change the state of the button or do whatever you want
				        Log.i(TAG, "Logged in");
				    }

				    @Override
				    public void onNotAcceptingPermissions()
				    {
				        Log.w(TAG, "User didn't accept read permissions");
				    }

				};

				// login
				mFacebook.login(onLoginListener);	
			
				// create publish listener
				OnPublishListener onPublishListener = new SimpleFacebook.OnPublishListener()
				{

				    @Override
				    public void onFail(String reason)
				    {
				        // insure that you are logged in before publishing
				        Log.w(TAG, reason);
				        Toast.makeText(SelectSectionActivity.this, "자랑하기에 실패했어요..다시한번 시도해주세요!", Toast.LENGTH_SHORT).show();
				    }

				    @Override
				    public void onException(Throwable throwable)
				    {
				        Log.e(TAG, "Bad thing happened", throwable);
				        Toast.makeText(SelectSectionActivity.this, "자랑하기에 실패했어요..다시한번 시도해주세요!", Toast.LENGTH_SHORT).show();
					    
				    }

				    @Override
				    public void onThinking()
				    {
				        // show progress bar or something to the user while publishing
				        Log.i(TAG, "In progress");
				    }

				    @Override
				    public void onComplete(String id)
				    {
				        Log.i(TAG, "Published successfully. id = " + id);
				        Toast.makeText(SelectSectionActivity.this, "페이스북에 자랑했어요!", Toast.LENGTH_SHORT).show();
				    }
				};

				String message = "포토로직에서 '"+logicName+"'로직을 "+time+
			    		"만에 완성했어요!"+"\n\n" +"함께 즐기시려면 다음 링크를 눌러주세요! "+"\n"+"-> https://play.google.com/store/apps/details?id=com.photologics.main";
				
				// create Photo instace and add some properties
				Photo photo = new Photo(LogicHelper.db.getBitmap(logicName));
				photo.addDescription(message);

				// publish photo to app album
				mFacebook.publish(photo, onPublishListener);
			
			}
		});
		
//		if(savedInstanceState == null){
//			Bundle b = new Bundle();
//			b.putString("name", logicName);
//	        facebookFragment = new FacebookFragment();
//	        facebookFragment.setArguments(b);
//	        getSupportFragmentManager()
//	        .beginTransaction()
//	        .add(android.R.id.content, facebookFragment)
//	        .commit();
//		}
//		else{
//	   
//	        // Or set the fragment from restored state info
//	        facebookFragment = (FacebookFragment) getSupportFragmentManager()
//	        .findFragmentById(android.R.id.content);
//		} 
		
 

	}

	
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_select_section, menu);
		return true;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v.getId() == R.id.grid_section) {
			if (event.getAction() == MotionEvent.ACTION_DOWN
					|| event.getAction() == MotionEvent.ACTION_MOVE) {
				float pntX = event.getX();
				float pntY = event.getY();

				final int indCol = (int) (pntX / sectionState[0][0].getWidth());
				final int indRow = (int) (pntY / sectionState[0][0].getHeight());

				if (indRow >= 0 && indCol >= 0 && indRow < sectionCount
						&& indCol < sectionCount) {
					if (Completenss[indRow][indCol] != 100) {
						LogicHelper.currentSection = new Point(indRow, indCol);
						Intent intent = new Intent(SelectSectionActivity.this,
								LogicActivity.class);
						intent.putExtra("x", indRow);
						intent.putExtra("y", indCol);
						startActivity(intent);
					}
				}
			}
		}
		// TODO Auto-generated method stub
		return false;
	}
	protected void onPause() {
		LogicHelper.backgroundMusic.onPause(getApplicationContext());
		super.onPause();
	}

	@Override
	protected void onResume() {
		LogicHelper.backgroundMusic.onStart();
		super.onResume();
		mFacebook = SimpleFacebook.getInstance(this);
	}
	@Override
	public void onBackPressed() {
		Intent it = new Intent(SelectSectionActivity.this,
				SelectLogicActivity.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(it);
		finish();

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
	    mFacebook.onActivityResult(this, requestCode, resultCode, data); 
	    super.onActivityResult(requestCode, resultCode, data);
	} 

}
